<template>
  <el-card class="mt-20 mr-20" shadow="never">
    <el-form ref="formRef" :rules="rules" :model="form" label-width="200px" label-position="left" class="form-readonly">
      <el-form-item :label="$t('pageStr.userNameStr')" style="max-width: 500px">
        <div class="w-full readonly__wrap">{{ localGet('token')?.uname }}</div>
      </el-form-item>
      <el-form-item :label="$t('pageStr.curPasswordStr')" prop="auth" style="max-width: 500px">
        <el-input v-model="form.auth" clearable/>
      </el-form-item>
      <el-form-item :label="$t('pageStr.newPasswordStr')" prop="newPassword" style="max-width: 500px">
        <el-input v-model="form.newPassword" type="password" show-password clearable/>
      </el-form-item>
      <el-form-item :label="$t('pageStr.newPassConfirmStr')" prop="surePassword" style="max-width: 500px">
        <el-input v-model="form.surePassword" type="password" show-password clearable/>
      </el-form-item>

    </el-form>
  </el-card>
  <el-button style="margin-top: 20px;width: 110px;color: #fff" color="#C29B74" @click="handleSubmit">
    {{ $t('tabsStr.applyStr') }}
  </el-button>
</template>

<script setup>
import {ref} from 'vue'
import {reqSetPassWord} from '@/api/users/user-manage'
import {ElMessage} from "element-plus";
import {useI18n} from 'vue-i18n'

import {localGet, encrypt} from '@/utils'

const {t} = useI18n()
const rules = {
  auth: [{required: true, message: t('emptyTip'), trigger: 'blur'}],
  newPassword: [{required: true, message: t('emptyTip'), trigger: 'blur'}],
  surePassword: [
    {required: true, message: t('emptyTip'), trigger: 'blur'},
    {validator: validatePassword,message: t('surePwdTip'), trigger: 'blur'}
  ]
}
const formRef = ref(null)
const form = ref({
  auth: '',
  newPassword: '',
  surePassword: ''
})

/**
 * 验证两次密码一致
 * @param rule
 * @param value
 * @param callback
 */
function validatePassword(rule, value, callback) {
  if (value !== form.value.newPassword) {
    callback(new Error('The passwords do not match'))
  } else {
    callback()
  }
}

function handleSubmit() {
  formRef.value.validate((valid) => {
    if (!valid) {
      return
    }
    const submitForm = {
      uname: localGet('token')?.uname,
      auth: encrypt(form.value.auth),
      newPassword: encrypt(form.value.newPassword)
    }
    console.log('修改密码', submitForm)
    reqSetPassWord(submitForm).then((res) => {
      console.log(res)
      if (res.passwdSet == 0) {
        ElMessage.success(t('successTip'))
      } else {
        ElMessage.error(t('errorTip'))
      }
    }).catch(() => {
      ElMessage.error(t('errorTip'))
    })
  })
}
</script>

<style scoped>
</style>